package com.sanqing.iframe;

import com.sanqing.dao.Dao;
import com.sanqing.model.BookType;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.event.MouseInputAdapter;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BooktypeModFrame extends JInternalFrame {
    private JTextField typeId;
    private JTextField typeName;
    private Map<Integer, BookType> map = new HashMap<>();
    private String[] columnNames;
    private JTable table;

    private Object[][] getFileStates(List<BookType> list) {
        columnNames = new String[]{"类别编号", "类别名称"};
        Object[][] results = new Object[list.size()][columnNames.length];
        for (int i = 0; i < list.size(); i++) {
            BookType bookType = list.get(i);
            results[i][0] = bookType.getId();
            results[i][1] = bookType.getTypeName();
            map.put(bookType.getId(), bookType);
        }
        return results;
    }

    public BooktypeModFrame() {
        super();
        final BorderLayout borderLayout = new BorderLayout();
        getContentPane().setLayout(borderLayout);
        setIconifiable(true);
        setClosable(true);
        setTitle("图书类别信息修改");
        setBounds(100, 100, 500, 400);

        final JPanel mainPanel = new JPanel();
        final BorderLayout borderLayout_1 = new BorderLayout();
        borderLayout_1.setVgap(5);
        mainPanel.setLayout(borderLayout_1);
        mainPanel.setBorder(new EmptyBorder(5, 10, 5, 10));
        getContentPane().add(mainPanel);

        final JScrollPane scrollPane = new JScrollPane();
        mainPanel.add(scrollPane);

        List<BookType> bookTypeList = selectBookType();
        Object[][] results = getFileStates(bookTypeList);
        table = new JTable(results, columnNames) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 所有单元格都不可编辑
            }
        };
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.addMouseListener(new TableListener());
        scrollPane.setViewportView(table);

        // 扩大表格列宽
        table.getColumnModel().getColumn(0).setPreferredWidth(150); // 扩大类别编号列宽
        table.getColumnModel().getColumn(1).setPreferredWidth(300); // 扩大类别名称列宽
        scrollPane.setViewportView(table);
        
        final JPanel bookTypePanel = new JPanel();
        mainPanel.add(bookTypePanel, BorderLayout.SOUTH);
        final GridLayout gridLayout = new GridLayout(0, 4);
        gridLayout.setVgap(5);
        gridLayout.setHgap(5);
        bookTypePanel.setLayout(gridLayout);

        final JLabel typeIdLabel = new JLabel();
        typeIdLabel.setHorizontalAlignment(JLabel.CENTER);
        typeIdLabel.setText("类别编号");
        bookTypePanel.add(typeIdLabel);

        typeId = new JTextField(20);
        typeId.setEditable(false);
        bookTypePanel.add(typeId);

        final JLabel typeNameLabel = new JLabel();
        typeNameLabel.setHorizontalAlignment(JLabel.CENTER);
        typeNameLabel.setText("类别名称");
        bookTypePanel.add(typeNameLabel);

        typeName = new JTextField();
        bookTypePanel.add(typeName);

        final JPanel bottomPanel = new JPanel();
        bottomPanel.setBorder(new LineBorder(SystemColor.activeCaptionBorder, 1, false));
        getContentPane().add(bottomPanel, BorderLayout.SOUTH);

        final FlowLayout flowLayout = new FlowLayout();
        flowLayout.setVgap(2);
        flowLayout.setHgap(30);
        flowLayout.setAlignment(FlowLayout.RIGHT);
        bottomPanel.setLayout(flowLayout);

        final JButton updateButton = new JButton();
        updateButton.addActionListener(new UpdateBookTypeActionListener());
        updateButton.setText("修改");
        bottomPanel.add(updateButton);

        final JButton deleteButton = new JButton();
        deleteButton.addActionListener(new DeleteBookTypeActionListener());
        deleteButton.setText("删除");
        bottomPanel.add(deleteButton);

        final JButton closeButton = new JButton();
        closeButton.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                doDefaultCloseAction();
            }
        });
        closeButton.setText("关闭");
        bottomPanel.add(closeButton);

        setVisible(true);
    }

    private List<BookType> selectBookType() {
        List<BookType> bookTypeList = new ArrayList<>();
        String sql = "SELECT id, typename FROM tb_booktype";
        ResultSet rs = Dao.executeQuery(sql);
        try {
            while (rs.next()) {
                BookType bookType = new BookType();
                bookType.setId(rs.getInt("id"));
                bookType.setTypeName(rs.getString("typename"));
                bookTypeList.add(bookType);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return bookTypeList;
    }

    public class TableListener extends MouseInputAdapter {
        @Override
        public void mouseClicked(final MouseEvent e) {
            int selRow = table.getSelectedRow();
            typeId.setText(table.getValueAt(selRow, 0).toString().trim());
            typeName.setText(table.getValueAt(selRow, 1).toString().trim());
        }
    }

    public class UpdateBookTypeActionListener implements ActionListener {
        @Override
        public void actionPerformed(final ActionEvent e) {
            int id = Integer.parseInt(typeId.getText());
            String newTypeName = typeName.getText().trim();

            if (isTypeNameDuplicate(id, newTypeName)) {
                JOptionPane.showMessageDialog(null, "该类别名称已存在，禁止修改", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            if (newTypeName.isEmpty()) {
                JOptionPane.showMessageDialog(null, "类别名称不能为空", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            String sql = "UPDATE tb_booktype SET typename = '" + newTypeName + "' WHERE id = " + id;
            int i = Dao.executeUpdate(sql);
            if (i == 1) {
                JOptionPane.showMessageDialog(null, "修改成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                Object[][] results = getFileStates(selectBookType());
                DefaultTableModel model = new DefaultTableModel();
                table.setModel(model);
                model.setDataVector(results, columnNames);
                table.getColumnModel().getColumn(0).setPreferredWidth(150); // 扩大类别编号列宽
                table.getColumnModel().getColumn(1).setPreferredWidth(300); // 扩大类别名称列宽
            } else {
                JOptionPane.showMessageDialog(null, "修改失败", "失败", JOptionPane.ERROR_MESSAGE);
            }
        }

        private boolean isTypeNameDuplicate(int currentId, String newTypeName) {
            String sql = "SELECT id, typename FROM tb_booktype";
            ResultSet rs = Dao.executeQuery(sql);
            try {
                while (rs.next()) {
                    int id = rs.getInt("id");
                    String typeName = rs.getString("typename");
                    if (id != currentId && typeName.equals(newTypeName)) {
                        return true;
                    }
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally {
                try {
                    if (rs != null) rs.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            return false;
        }
    }

    public class DeleteBookTypeActionListener implements ActionListener {
        @Override
        public void actionPerformed(final ActionEvent e) {
            int selRow = table.getSelectedRow();
            if (selRow == -1) {
                JOptionPane.showMessageDialog(null, "请选择要删除的类别", "提示", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            int typeIdToDelete = Integer.parseInt(table.getValueAt(selRow, 0).toString());
            String sql = "DELETE FROM tb_booktype WHERE id = " + typeIdToDelete;
            int i = Dao.executeUpdate(sql);
            if (i == 1) {
                JOptionPane.showMessageDialog(null, "删除成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                Object[][] results = getFileStates(selectBookType());
                DefaultTableModel model = new DefaultTableModel();
                table.setModel(model);
                model.setDataVector(results, columnNames);
                table.getColumnModel().getColumn(0).setPreferredWidth(150); // 扩大类别编号列宽
                table.getColumnModel().getColumn(1).setPreferredWidth(300); // 扩大类别名称列宽
            } else {
                JOptionPane.showMessageDialog(null, "删除失败", "失败", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}